# -*- coding: utf-8 -*-
from sqlalchemy.sql.expression import func

from application import db
from common.libs.Helper import ops_render, iPagenation
from common.libs.UrlManager import UrlManager
from common.models.movie import Movie
from flask import Blueprint, request, redirect

index_page = Blueprint("index_page", __name__)

"""
默认页的后端
"""


@index_page.route("/")
def index():
	return ops_render("index.html")


@index_page.route("/movie")
def movie():
	# 拿到前端请求参数
	req = request.values
	# 参数是这样的：/?order=last  或者 /?order=hot   默认就是last
	order_by_f = str(req["order"]) if ("order" in req and req['order']) else "last"
	# 前端请求页面：默认页数是第一页
	page = 1
	# 如果前端有指定的页数就按前端的参数来修改
	if 'p' in req and req['p']:
		page = int(req['p'])
	# movie表中查询
	query = Movie.query
	# 构建一个关于页面的参数字典：数据库中电影的总数、一个页面包含的电影数量、前端请求的页面、页面的url参数后缀
	page_params = {
		'total_count': query.count(),
		"page_size": 16,
		'page': page,
		'url': "/movie?"
	}
	# 传给专门处理分页的函数，进一步构建关于分页的参数
	pages = iPagenation(page_params)
	# [0 - 16),[16 - 32),[60 - 90)
	# 对应[
	offset = (page - 1) * page_params['page_size']
	# 对应）
	limit = page * page_params['page_size']
	# 如果前端指定按热度排序
	if order_by_f == "hot":
		# 就首先按view_counter倒序排
		query = query.order_by(Movie.view_counter.desc(), Movie.id.desc())
	else:
		# 要是前端指定按更新日期排，就首先按updated_time倒序排
		query = query.order_by(Movie.updated_time.desc(), Movie.id.desc())
	# 取出相应的数量
	list_movie = query[offset:limit]
	# 传递给前端
	return ops_render("movie.html", {"data": list_movie, "pages": pages})


@index_page.route("/info")
def info():
	req = request.values
	id = int(req['id']) if ('id' in req and req['id']) else 0
	if id < 1:
		return redirect(UrlManager.buildUrl("/"))

	info = Movie.query.filter_by(id=id).first()
	if not info:
		return redirect(UrlManager.buildUrl("/"))

	'''
	更新阅读数量
	'''
	info.view_counter += 1
	db.session.add(info)
	db.session.commit()
	'''
	获取推荐
	'''
	recommend_list = Movie.query.order_by(func.rand()).limit(4)
	return ops_render("info.html", {"info": info, "recommend_list": recommend_list})
